package com.webull.information.center.carwler.task.support;

import java.util.Date;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.webull.information.center.carwler.common.model.BranchNews;
import com.webull.information.center.carwler.common.model.NewsInformation;
import com.webull.information.center.carwler.common.util.BranchNewsUtil;
import com.webull.information.center.carwler.common.util.CarwlerJobStateUtil;
import com.webull.information.center.carwler.common.util.HttpClientUtil;
import com.webull.information.center.carwler.common.util.ThumbnailatorUtil;
import com.webull.information.center.carwler.common.util.ThumbnailatorUtil.NewsThumb;
import com.webull.information.center.carwler.common.util.aws.s3.AwsS3ClientUtil;
import com.webull.information.center.carwler.common.util.aws.s3.AwsUsS3ClientUtil;
import com.webull.information.center.carwler.common.util.news.NewsWrapperUtil;
import com.webull.information.center.carwler.service.CarwlerNewsService;
import com.webull.information.client.model.News;
import com.webull.information.client.model.parm.NewsRelType;
import com.webull.information.client.service.InfoNewsService;
import com.webull.picture.client.PictureService;
import com.webull.picture.client.model.PictureFile;
import com.webull.securities.client.model.TickerRel;
import com.webull.securities.client.service.StockService;

/**
 * 资讯处理类
 *
 * @author shimingjun
 * @version 1.0
 * @date 2016年8月18日 下午3:16:28
 * @since JDK 1.8
 */
@Component
public class NewsProcessorSupport {
    protected final Logger logger = LogManager.getLogger(getClass());

    private @Autowired
    InfoNewsService infoNewsService;
    private @Autowired
    CarwlerNewsService carwlerNewsService;
    private @Autowired
    NewsWrapperUtil newsWrapperUtil;
    private @Autowired
    AwsS3ClientUtil awsS3ClientUtil;
    private @Autowired
    AwsUsS3ClientUtil awsUsS3ClientUtil;
    private @Autowired
    HttpClientUtil httpClientUtil;
    private @Autowired
    PictureService pictureService;
    private @Autowired
    StockService stockService;
    private @Autowired
    CarwlerJobStateUtil carwlerJobStateUtil;
    private final String storeFormat = "html";// 当前存储网页格式2

    @SuppressWarnings("unused")
    protected void productionNewsInfoRecord(Integer targetId,String targetMd5, NewsRelType reltype, NewsInformation info) {

        Long newsId = info.getNewsId();
        News news = new News();
        news.setId(newsId);

        BeanUtils.copyProperties(info, news, "siteType", "content", "mainPic");
        if (info.getSiteType() != null)
            news.setSiteType(info.getSiteType());// news自带siteType默认值
        if (news.getHomePage() != null) {
            // 存在homePage标识的情况下不处理
        } else if (NewsRelType.homePage.equals(reltype) || !News.CollectSource.reutersGuide.equals(info.getCollectSource())) {
            news.setHomePage(News.HomeType.home);
        }

        if (StringUtils.isBlank(news.getUrlMd5()))
            return;

        news.setStoreFormat(storeFormat);
        news.setSyncUs(true);// 字段已过时，以后增加s3时作为标记可用

        fir_if:
        for (String mainPic : info.getMainPic().getMainPic()) {// 选择更合适的图片
            byte[] contexts = httpClientUtil.getByteEntity(mainPic, info.getMainPic().isMainProxy());
            if (contexts != null && contexts.length > 0) {
                NewsThumb newsThumb = ThumbnailatorUtil.converNewsThumb(contexts,
                        Optional.ofNullable(info.getMainPic().getThumSize()).orElse(250));
                if (newsThumb != null) {
                    PictureFile file = new PictureFile();
                    file.setName(newsThumb.getName());
                    file.setBytes(newsThumb.getBytes());
                    String pubKey = pictureService.uploadPicture("news_thumb", file);
                    news.setMainPic(newsThumb.getName());
                    break fir_if;
                }
            }
        }

        if (News.SiteType.PIRORIT.equals(news.getSiteType())) {
            newsId = this.bindNewsRecord(targetId, targetMd5,reltype, news);
        } else {
            String shard = Optional.ofNullable(StringUtils.stripToNull(info.getStoreShard()))//
                    .orElse(DateFormatUtils.format(new Date(), "yyyyMMdd"));
            String file = shard + "/" + info.getUrlMd5() + "." + storeFormat;
            try {
                NewsWrapperUtil.HtmlResult result = newsWrapperUtil.newsHtmlFile(info);
                /*
                 * 确保上传是成功的
				 */
                if (awsS3ClientUtil.uploadNewsHtml(file, result.getHtml())//
                        && awsUsS3ClientUtil.uploadNewsHtml(file, result.getHtml())) {

                    news.setStoreVersion(result.getVersion());
                    news.setStoreShard(shard);
                    newsId = this.bindNewsRecord(targetId,targetMd5, reltype, news);
                }
			} catch (Exception e) {
				logger.error("news context save failed3!!!!!", e);
            }
        }

		info.setNewsId(newsId);
		this.bindHuGangTong(targetId, reltype, newsId, info.getSumMd5());

    }




    /**
     * 沪港通关系绑定
     *
     * @param targetId
     * @param relType
     * @param newsId
     */
	private void bindHuGangTong(Integer targetId, NewsRelType relType, Long newsId, String sumMd5) {
        if (carwlerJobStateUtil.isCarwlerBase())
			if (newsId != null && NewsRelType.ticker.equals(relType)) {
                TickerRel rel = new TickerRel();
                rel.setSourceTickerId(targetId);
                Optional.ofNullable(stockService.searchTickerRel(rel))//
                        .ifPresent(v -> v.forEach(v0 -> {
							if (this.getBySumMd5(sumMd5, relType, v0.getTargetTickerId(), null) == null) {
								addNewsInfoRel(v0.getTargetTickerId(), relType, newsId.intValue());
								logger.info("news context addNewsInfoRel newsId_ :{},targetId:{},TargetTickerId:{}",
										newsId, targetId, v0.getTargetTickerId());
							}
                        }));
            }
    }

    /**
     * base将异地采集的branchNews入库
     *
     * @param branchNews
     */
    protected Long bindBranchNewsAndRel(BranchNews branchNews, Long dbNewsId) {
        News myNews = new News();
        BeanUtils.copyProperties(branchNews, myNews, "id");
        myNews.setId(dbNewsId);
        Integer targetId = branchNews.getTargetId();
        NewsRelType relType = BranchNewsUtil.genNewsRelType(branchNews.getTargetType());
        Long newsId = infoNewsService.bindNewsRecord(targetId, relType, myNews);
		bindHuGangTong(targetId, relType, newsId, myNews.getSumMd5());
        return newsId;
    }


    protected void addNewsInfoRel(Integer targetId, NewsRelType type, Integer newsId) {
        if (carwlerJobStateUtil.isCarwlerBase()) {
            infoNewsService.addNewsInfoRel(targetId, type, newsId);
        } else {
            carwlerNewsService.addExistNewsInfoRel(targetId, type, newsId);
        }
    }

    protected Long bindNewsRecord(Integer targetId,String targetMd5, NewsRelType type, News news) {
        if (carwlerJobStateUtil.isCarwlerBase()) {
            return infoNewsService.bindNewsRecord(targetId, type, news);
        } else {//增加流水记录
            carwlerNewsService.addBranchNewsRecord(targetId,targetMd5, type, news);
            return null;
        }
    }

    protected News getByUrlMd5(String ulrMd5) {
        return infoNewsService.getByUrlMd5(ulrMd5);
    }

    protected News getBranchNewsByUrlMd5(String ulrMd5, Integer targetId, NewsRelType type) {
        return infoNewsService.getByUrlMd5(ulrMd5);
    }


	protected News getBySumMd5(String sumMd5, NewsRelType type, Integer targetId, Date time) {
		return infoNewsService.getBySumMd5(sumMd5, type, targetId, time);
    }

    protected void updateNewsS3(News dbNews, NewsInformation info) {

        String shard = StringUtils.isNotBlank(dbNews.getStoreShard()) ? dbNews.getStoreShard()
                : DateFormatUtils.format(new Date(), "yyyyMMdd");
        String file = shard + "/" + info.getUrlMd5() + "." + storeFormat;

        try {
            NewsWrapperUtil.HtmlResult result = newsWrapperUtil.newsHtmlFile(info);
            if (awsS3ClientUtil.uploadNewsHtml(file, result.getHtml()) //
                    && awsUsS3ClientUtil.uploadNewsHtml(file, result.getHtml())) {
                News news = new News();
                Optional.ofNullable(StringUtils.stripToNull(info.getTitle())).ifPresent(s0 -> {
                    news.setTitle(s0);
                    news.setSumMd5(info.getSumMd5());// 标题摘要
                });
                Optional.ofNullable(StringUtils.stripToNull(info.getSourceName()))
                        .ifPresent(s0 -> news.setSourceName(s0));
                Optional.ofNullable(info.getNewsTime()).ifPresent(s0 -> news.setNewsTime(s0));
                news.setId(dbNews.getId());
                news.setUrlMd5(info.getUrlMd5());
                news.setStoreVersion(result.getVersion());
                news.setStoreShard(shard);
                news.setStoreFormat(storeFormat);
                infoNewsService.update(news);
            }
        } catch (Exception e) {
            logger.error("news context save failed!!!!", e);
        }

    }

}
